<?php
namespace Modules\Market\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Market\Entities\Tenant;
use Modules\Asset\Entities\Resale;

use Validator;
use ThrowException;
use Auth;
use DB;

class TransactionController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'resale_id' => ['required'],
            'tenant_id' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        $tenant = Tenant::getEntity([
            'id' => $req->tenant_id
        ]);

        $resale = Resale::getEntity([
            'id' => $req->resale_id
        ]);

        $resale->completeWithTenant($tenant);

        // $item = Tenant::create($info);

        return [
        ];
    }

    // 批量购买
    public function batchBuy(Request $req)
    {
        $rule = [
            'tenant_id' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        $tenant = Tenant::getEntity([
            'id' => $req->tenant_id
        ]);

        // $list = Resale::getEntity([
        //     'id' => $req->resale_id
        // ]);

        $list = Resale::where('is_allow_fast_match', 1)->status('pending')->get();

        if ($list->count() === 0) {
            ThrowException::Conflict('当前可批量购买的转售数量为0');
        }

        DB::beginTransaction();

        foreach ($list as $resale) {
            $resale->completeWithTenant($tenant);
        }

        DB::commit();

        // $item = Tenant::create($info);

        return [
            'total' => $list->count()
        ];
    }
}
